package com.jinxiangyang.controller;

import com.jinxiangyang.annotation.OperateLog;
import com.jinxiangyang.domain.vo.FileChunkDTO;
import com.jinxiangyang.domain.vo.FileChunkResultDTO;
import com.jinxiangyang.service.IUploadService;
import com.jinxiangyang.utils.enums.BusinessType;
import com.jinxiangyang.utils.enums.OperatorType;
import com.jinxiangyang.utils.result.AjaxResult;

import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("upload")
@CrossOrigin
@Api(tags = "分片上传文件")
public class UploaderController {

    @Autowired
    private IUploadService uploadService;

    @GetMapping("chunk")
    @OperateLog(title = "分片上传文件", operatorType = OperatorType.TEACHER, businessType = BusinessType.OTHER)
    public AjaxResult checkChunkExist(FileChunkDTO chunkDTO) {
        FileChunkResultDTO fileChunkCheckDTO;
        try {
            fileChunkCheckDTO = uploadService.checkChunkExist(chunkDTO);
            return AjaxResult.success(fileChunkCheckDTO);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    @PostMapping("chunk")
    @OperateLog(title = "分片上传文件", operatorType = OperatorType.ADMIN, businessType = BusinessType.UPDATE)
    public AjaxResult uploadChunk(FileChunkDTO chunkDTO) {
        try {
            uploadService.uploadChunk(chunkDTO);
            return AjaxResult.success(chunkDTO.getIdentifier());
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 请求合并文件分片
     *
     * @param chunkDTO
     * @return
     */
    @PostMapping("merge")
    @OperateLog(title = "分片上传文件", operatorType = OperatorType.TEACHER, businessType = BusinessType.OTHER)
    public AjaxResult mergeChunks(@RequestBody FileChunkDTO chunkDTO) {
        try {
            if(Boolean.TRUE.equals(uploadService.mergeChunk(chunkDTO.getIdentifier(), chunkDTO.getFilename(), chunkDTO.getTotalChunks()).getIsSuccess())){
                return AjaxResult.success(uploadService.mergeChunk(chunkDTO.getIdentifier(), chunkDTO.getFilename(), chunkDTO.getTotalChunks()).getIsSuccess());
            }
            return AjaxResult.error();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

}
